from django import forms
from django.template.loader import render_to_string
from django.forms.util import flatatt
from django.forms.widgets import Media
from django.utils.safestring import mark_safe

from pypsqueak.group.models import Group, Assignment, Membership
from pypsqueak.chrome.widgets import *
from pypsqueak.chrome.forms import ComboForm, ChromeModelForm

# ASSIGNMENTS

class AssignmentInsertForm(ChromeModelForm):
	description = forms.CharField(widget=forms.Textarea, required=False)

	class Meta:
		model = Assignment
		exclude = ('pages','order')

class AssignmentGroupInsertForm(AssignmentInsertForm):
	""" Assignment form that defaults a group """
	group = forms.CharField(widget=forms.HiddenInput)

	def __init__(self, group, *args, **kwargs):
		super(AssignmentGroupInsertForm, self).__init__(*args,**kwargs)
		self.fields['group'].initial = group


class AssignmentUpdateForm(ChromeModelForm):
	description = forms.CharField(widget=ChromeTextareaWidget)
	due_date = forms.DateField(widget=ChromeDateWidget)

	class Meta:
		model = Assignment
		exclude = ('group','pages','order')



class AssignmentAjaxInsertForm(ChromeModelForm):
	"""
	Form using AJAX to insert assignments.
	Requires setting master_object for group ownership of new assignments.
	"""
	title = forms.CharField( required=True )
	group = forms.ModelChoiceField( Group.objects.all(), widget=forms.HiddenInput)


	def set_master(self, group):
		""" Set the group pk value """
		self.fields['group'].queryset = Group.objects.filter(pk=group.pk)
		self.fields['group'].initial=group.pk


	def as_template(self):
		return render_to_string('group/AssignmentAjaxInsertForm.html',
							{'form':self,'url':Assignment.get_insert_url(),
							 'name':self.prefix })


	class Media:
		js = ("/files/lib/jquery/js/jquery-1.3.2.min.js",)

	class Meta:
		model = Assignment
		exclude = ('pages','description','order')


class AssignmentInlineUpdateForm(ChromeModelForm):
	title = forms.CharField(
				#widget=AjaxCharWidget(),
				label="Title" )
	order = forms.IntegerField(
				widget=forms.HiddenInput(),
				label="Order" )
	delete_me = forms.BooleanField(
				#widget=AjaxDeleteMeWidget(),
				required=False,
				label="Delete" )
	description = forms.CharField(
				widget=ChromeTextareaWidget( attrs={'rows':'1'} ),
				required=False)
	due_date = forms.DateField(widget=ChromeDateWidget)


	def as_template(self):
		return render_to_string( 'group/AssignmentInlineUpdateForm.html',
								{'form': self,'url':self.instance.get_update_url() })


	class Media:
		css = {
            'all': ('/files/lib/jquery/css/base/ui.all.css',)
        }
		js = ('/files/lib/jquery/js/jquery-1.3.2.min.js',
				'/files/lib/jquery/js/ui.core.js',
				'/files/lib/jquery/js/ui.sortable.js',
				'/files/js/Group/AssignmentInlineUpdateForm.js',)


	class Meta:
		model = Assignment
		exclude = ('group','pages')


class AssignmentDeleteForm(ChromeModelForm):
	pass


# GROUPS


class GroupUpdateForm(ChromeModelForm):
	""" Update group properties, as well as attached assignments """
	start_date = forms.DateField(widget=ChromeDateWidget)
	end_date = forms.DateField(widget=ChromeDateWidget)
	description = forms.CharField(widget=ChromeTextareaWidget)


	class Media:
		js = ('/files/lib/jquery/js/jquery-1.3.2.min.js',
				'/files/lib/jquery/js/ui.core.js',
				'/files/lib/jquery/js/ui.tabs.js',)


	class Meta:
		model = Group
		exclude = ('users')

class GroupInsertForm(ChromeModelForm):
	""" Create a new group """
	start_date = forms.DateField(widget=ChromeDateWidget)
	end_date = forms.DateField(widget=ChromeDateWidget)
	description = forms.CharField(widget=ChromeTextareaWidget)

	class Meta:
		model = Group
		exclude = ('users')


class GroupDeleteForm(ChromeModelForm):
	pass


# Memberships

class MembershipAjaxInsertForm(ChromeModelForm):
	""" Used to add membership to a group """

	def set_master(self, group):
		""" Set the group pk value """

		# Update the group display options so it doesn't show and only allows
		#	one group as a valid option.
		self.fields['group'].queryset = Group.objects.filter(pk=group.pk)
		self.fields['group'].initial=group.pk
		self.fields['group'].widget=forms.HiddenInput()

		# Remove potential users who are already members.
		memberships = Membership.objects.filter(group=group)
		for membership in memberships:
			self.fields['user'].queryset = self.fields['user'].queryset.exclude(pk=membership.user.pk)


	def as_template(self):
		return render_to_string('group/MembershipAjaxInsertForm.html', {
							'form':self,
							'url':Membership.get_insert_url(),
							'name':self.prefix })

	class Meta:
		model = Membership


class MembershipInlineUpdateForm(ChromeModelForm):
	delete_me = forms.BooleanField(
				required=False,
				label="Remove" )

	def as_template(self):
		return render_to_string( 'group/MembershipInlineUpdateForm.html',
								{'form': self})


	class Media:
		css = {
            'all': ('/files/lib/jquery/css/base/ui.all.css',)
        }
		js = ('/files/lib/jquery/js/jquery-1.3.2.min.js',
				'/files/lib/jquery/js/ui.core.js',
				'/files/lib/jquery/js/ui.sortable.js',
				'/files/js/Group/AssignmentInlineUpdateForm.js',)


	class Meta:
		model = Membership
		exclude = ('group','user')